package com.wake.mycomposebook.ui.home

import android.annotation.SuppressLint
import android.content.Context
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Palette
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.SmallTopAppBar
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.wake.data.DemoDataProvider
import com.wake.data.model.HomeScreenItems
import com.wake.mycomposebook.ui.sys.AppThemeState
import com.wake.mycomposebook.utils.TestTags
import com.wake.theme.modifier.ColorPallet
import com.wake.theme.modifier.components.Material3Card
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

/**
 *@author created by WA03675
 *@date  2022-04-13 09:56
 *@des Demo上的HomeScreen
 */

@OptIn(ExperimentalMaterialApi::class, ExperimentalMaterial3Api::class)
@Composable
fun DemoHomeScreen(
    appThemeState: MutableState<AppThemeState>,
    chooseColorBottomModalState: ModalBottomSheetState
) {
    val showMenu = remember {
        mutableStateOf(false)
    }

    val coroutineScope = rememberCoroutineScope()

    Scaffold(
        modifier = Modifier
            .testTag(TestTags.HOME_SCREEN_ROOT),
        topBar = {
            SmallTopAppBar(
                title = {
                    Text(text = "Compose CookBook", style = MaterialTheme.typography.h5)
                },
                actions = {
                    IconButton(onClick = {
                        appThemeState.value = appThemeState.value.copy(darkTheme = !appThemeState.value.darkTheme)
                    }) {
                        Icon(painter = painterResource(id = com.wake.theme.R.drawable.ic_sleep), contentDescription = null)
                    }
                    ChangeColorIconButton(coroutineScope = coroutineScope, chooseColorBottomModalState = chooseColorBottomModalState, showMenu = showMenu)
                },
            )
        },
        content = {
            HomeScreenContent(appThemeState.value.darkTheme, showMenu) {
                appThemeState.value = appThemeState.value.copy(pallet = it)
                showMenu.value = false
            }
        }
    )
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun HomeScreenContent(
    isDarkTheme: Boolean,
    showMenu: MutableState<Boolean>,
    onPalletChange: (ColorPallet) -> Unit
) {
    val context = LocalContext.current
    val list = remember {
        DemoDataProvider.homeScreenListItems
    }
    val screenWidth = LocalConfiguration.current.screenWidthDp
    val isWiderScreen = screenWidth > 550
    Box(modifier = Modifier.fillMaxWidth()) {
        if (isWiderScreen) {
            LazyVerticalGrid(
                cells = GridCells.Adaptive(150.dp),
                contentPadding = PaddingValues(8.dp)
            ) {
                items(list, itemContent = {
                    HomeScreenListView(it, context, isDarkTheme, isWiderScreen)
                })
            }
        } else {
            LazyColumn(modifier = Modifier.testTag(TestTags.HOME_SCREEN_LIST)) {
                items(
                    items = list,
                    itemContent = {
                        HomeScreenListView(homeScreenItems = it, context = context, isDarkTheme = isDarkTheme, isWiderScreen = isWiderScreen)
                    }
                )
            }
        }
        if (showMenu.value) {
            PalletMenu(modifier = Modifier.align(Alignment.TopEnd), onPalletChange = onPalletChange)
        }
    }
}

@Composable
fun HomeScreenListView(homeScreenItems: HomeScreenItems, context: Context, isDarkTheme: Boolean, isWiderScreen: Boolean) {
    if (isWiderScreen) {
        Material3Card(modifier = Modifier
            .clickable {
                homeItemClicked(homeScreenItems, context, isDarkTheme)
            }
            .height(150.dp)
            .padding(8.dp),
            backgroundColor = androidx.compose.material3.MaterialTheme.colorScheme.primary,
            shape = RoundedCornerShape(8.dp),
            elevation = 4.dp,
            contentColor = androidx.compose.material3.MaterialTheme.colorScheme.onPrimary
        ) {
            Text(text = homeScreenItems.name, modifier = Modifier.padding(8.dp), style = androidx.compose.material3.MaterialTheme.typography.titleMedium)
        }
    } else {
        Button(
            onClick = { homeItemClicked(homeScreenItems, context, isDarkTheme) },
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
                .testTag(
                    "button-${homeScreenItems.name}"
                ),
            shape = RoundedCornerShape(15.dp)
        ) {
            Text(text = homeScreenItems.name, modifier = Modifier.padding(8.dp), style = androidx.compose.material3.MaterialTheme.typography.titleMedium)
        }
    }
}

fun homeItemClicked(homeScreenItems: HomeScreenItems, context: Context, isDarkTheme: Boolean) {

}


/**
 *调色板
 * @param coroutineScope
 * @param chooseColorBottomModalState
 */

@SuppressLint("CoroutineCreationDuringComposition")
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun ChangeColorIconButton(coroutineScope: CoroutineScope, chooseColorBottomModalState: ModalBottomSheetState, showMenu: MutableState<Boolean>) {

    val accessibilityManager = LocalContext.current.getSystemService(Context.ACCESSIBILITY_SERVICE) as android.view.accessibility.AccessibilityManager
    IconButton(onClick = {
        if (accessibilityManager.isEnabled && accessibilityManager.isTouchExplorationEnabled) {
            coroutineScope.launch {
                chooseColorBottomModalState.show()
            }
        } else {
            showMenu.value = !showMenu.value
        }
    }) {
        Icon(imageVector = Icons.Default.Palette, contentDescription = null)
    }

}

@OptIn(
    ExperimentalMaterialApi::class,
    ExperimentalFoundationApi::class
)
@Preview
@Composable
fun previewDemoHomeScreen() {
    val appThemeState = remember {
        mutableStateOf<AppThemeState>(AppThemeState(false, ColorPallet.GREEN))
    }
    val chooseColorBottomModalState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)

    DemoHomeScreen(appThemeState = appThemeState, chooseColorBottomModalState = chooseColorBottomModalState)

}